package com.nbcio.modules.estar.customerpriceh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.nbcio.modules.erp.base.entity.ErpCustomer;
import com.nbcio.modules.erp.base.service.IErpCustomerService;
import com.nbcio.modules.estar.customerprice.entity.Customerprice;
import com.nbcio.modules.estar.customerpriceh.entity.CustomerpriceH;
import com.nbcio.modules.estar.customerpriceh.entity.CustomerpriceB;
import com.nbcio.modules.estar.customerpriceh.mapper.CustomerpriceBMapper;
import com.nbcio.modules.estar.customerpriceh.mapper.CustomerpriceHMapper;
import com.nbcio.modules.estar.customerpriceh.service.ICustomerpriceBService;
import com.nbcio.modules.estar.customerpriceh.service.ICustomerpriceHService;
import com.nbcio.modules.flowable.apithird.service.FlowCallBackServiceI;
import com.nbcio.modules.flowable.apithird.service.FlowCommonService;
import com.nbcio.modules.flowable.apithird.business.entity.FlowMyBusiness;
import com.nbcio.modules.flowable.utils.StatusEnum;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Collection;
import java.util.Map;

/**
 * @Description: 客户价格
 * @Author: nbacheng
 * @Date:   2024-05-08
 * @Version: V1.0
 */
@Service("customerpriceHService")
public class CustomerpriceHServiceImpl extends ServiceImpl<CustomerpriceHMapper, CustomerpriceH> implements ICustomerpriceHService , FlowCallBackServiceI{



    @Autowired
    FlowCommonService flowCommonService;
	@Autowired
	private CustomerpriceHMapper customerpriceHMapper;
	@Autowired
	private CustomerpriceBMapper customerpriceBMapper;
	@Autowired
	private ICustomerpriceBService customerpriceBService;
	@Lazy
	@Resource
	private RedisUtil redisUtil;
	@Autowired
	private IErpCustomerService erpCustomerService ;
	public BigDecimal getPrice(String customerId, String goodsclass, String goodsid, BigDecimal bigDecimal){
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		ErpCustomer exist=null;
		if (customerId==null){
			QueryWrapper<ErpCustomer> queryWrapper=new QueryWrapper<>();
			queryWrapper.eq("phone", sysUser.getPhone());
			exist = erpCustomerService.getOne(queryWrapper);
			if (exist ==null ){
				return null;
			}
			customerId= exist.getId();
		}

		QueryWrapper<CustomerpriceH> query = new QueryWrapper<>();
		StringBuffer key = new StringBuffer();
		key.append(customerId);
		if (customerId == null){
			return null;
		}
		query.eq("customer", customerId);


		java.math.BigDecimal price = (BigDecimal) redisUtil.get(key.toString());
		//如果缓存有数据就直接返回
		if (price!=null){
			return price;
		}
		List<CustomerpriceH> goodslist= this.list(query);
		//没有客户去找客户分类
		if (CollectionUtils.isEmpty(goodslist)){
			QueryWrapper<CustomerpriceH> queryclass = new QueryWrapper<>();

			queryclass.eq("materialclass", exist.getCustCode());
			queryclass.isNotNull("customer");
			goodslist= this.list(query);
		}
		if (!CollectionUtils.isEmpty(goodslist)){
			String pk_h=goodslist.get(0).getId();
			QueryWrapper<CustomerpriceB> queryBVo = new QueryWrapper<>();
			queryBVo.eq("pk_h", pk_h);
			queryBVo.eq("goodsid", goodsid);
			List<CustomerpriceB>  listBvo =  customerpriceBService.list(queryBVo);
			//找物料
			if (!CollectionUtils.isEmpty(listBvo)){
				price= listBvo.get(0).getPrice();
				key.append(goodsid);
				redisUtil.set(key.toString(), price,3600);
				return price;
			}else {
				//找物料分类
				key=new StringBuffer();
				key.append(customerId).append(goodsclass);
				BigDecimal zk= (BigDecimal) redisUtil.get(key.toString());
				//找缓存的数据
				if (zk!=null){
					price= zk.multiply(bigDecimal).divide(new BigDecimal(10));
					return price;
				}
				QueryWrapper<CustomerpriceB> queryClassBVo = new QueryWrapper<>();
				queryClassBVo.eq("pk_h", pk_h);
				queryClassBVo.eq("goodsclass", goodsclass);

				//物料分类只能找折扣
				List<CustomerpriceB>  listClassBvo =customerpriceBService.list(queryClassBVo);

				if (!CollectionUtils.isEmpty(listClassBvo)){
					redisUtil.set(key.toString(), listClassBvo.get(0).getDiscount());
					price= listClassBvo.get(0).getDiscount().multiply(bigDecimal).divide(new BigDecimal(10));
					return price;
				}

			}



		}


		//如果为空就去找物料分类
//		if (!CollectionUtils.isEmpty(goodslist)){
//			price= goodslist.get(0).getPrice();
//			redisUtil.set(key.toString(), price);
//			return price;
//		}else {
//
//		}


		return null;
	}
	@Override
	@Transactional
	public void saveMain(CustomerpriceH customerpriceH, List<CustomerpriceB> customerpriceBList) {
		customerpriceHMapper.insert(customerpriceH);
		if(customerpriceBList!=null && customerpriceBList.size()>0) {
			for(CustomerpriceB entity:customerpriceBList) {
				//外键设置
				entity.setPkH(customerpriceH.getId());
				customerpriceBMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(CustomerpriceH customerpriceH,List<CustomerpriceB> customerpriceBList) {
		customerpriceHMapper.updateById(customerpriceH);

		//1.先删除子表数据
		customerpriceBMapper.deleteByMainId(customerpriceH.getId());

		//2.子表数据重新插入
		if(customerpriceBList!=null && customerpriceBList.size()>0) {
			for(CustomerpriceB entity:customerpriceBList) {
				//外键设置
				entity.setPkH(customerpriceH.getId());
				customerpriceBMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		customerpriceBMapper.deleteByMainId(id);
		customerpriceHMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			customerpriceBMapper.deleteByMainId(id.toString());
			customerpriceHMapper.deleteById(id);
		}
	}
    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        flowCommonService.delActBusiness(id.toString());
        return super.removeById(id);
    }
    /**
     * 流程处理完成后的回调
     * @param business 里面包含流程运行的现状信息，业务层可根据其信息判断，书写增强业务逻辑的代码，<br/>
     *                 1、比如将其中关键信息存入业务表，即可单表业务操作,否则需要关联flow_my_business表获取流程信息<br/>
     *                 2、比如在流程进行到某个节点时(business.taskId)，需要特别进行某些业务逻辑操作等等<br/>
     */
      @Override
      public void afterFlowHandle(FlowMyBusiness business) {

           business.getTaskNameId();//接下来审批的节点
           business.getValues();//前端传进来的参数
           business.getActStatus();//流程状态 ActStatus.java
           //....其他
           CustomerpriceH   customerpriceH= this.getById(business.getDataId());
           //customerpriceH.setActstatus(StatusEnum.getEnumKey(business.getActStatus()));
           // customerpriceH.
             this.updateById(customerpriceH);
        }


   /**
     * 根据业务id返回业务表单数据<br/>
     * @param dataId
     * @return
     */
        @Override
        public Object getBusinessDataById(String dataId) {
            return this.getById(dataId);
        }
    /**
     * 返回当前节点的流程变量
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
            return null;
        }
    /**
     * 返回当前节点的候选人username
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
            // 通过当前节点来判断下一个节点的候选人并写回到反参中，如果为null，流程模块会根据默认设置处理

            return null;
        }


        @Override
        public void relationAct(String dataId) {
             //flowCommonService.initActBusiness("实验授课申请：dataId"+dataId,dataId,"customerpriceHService","process_tpho5a4q","process_tpho5a4q:4:32128f7c-ce77-11ec-843e-927841cf098b");
        }

}
